<template>
<!--  <PcLayout>-->
  <div class="home-wrap">

    <div class="today-dishes-scroll">
      <div v-if="loadingDishes" class="loading">Loading...</div>
      <div v-else class="dishes-scroll-container">
        <div class="dish-card" v-for="dish in todayDishes" :key="dish.dish_id">
          <img :src="getImageUrl(dish.image_url)" alt="Image of the dish" class="dish-image" />
          <div class="dish-info">
            <h3 class="dish-name">{{ dish.name }}</h3>
          </div>
        </div>
      </div>
    </div>
<!--    <DishDetailCard :dish="selectedDish" v-if="showModal" @close="closeModal"/>-->


        <div class="play-container">
      <div class="bg"></div>
      <div class="container">
        <div
            class="left"
        >
          <video id="live-video" controls style="width: 100%; height: 100%;" muted></video>
          <div
              class="cdn-ico"
          >
          </div>
          <div
              class="cover"
          ></div>
        </div>
        <div class="right">
          <div
              class="list"
          >
            <div>
              <div class="hidden">
                <div
                    class="cdn-ico">
                  <div class="txt">不同视角轮播</div>
                  <div v-for="(stream, index) in liveStreams" :key="index" class="stream-card" @click="switchLiveStream(stream.url)">
                    <div class="stream-thumbnail"><!-- 这里可以放置缩略图或其他标识 --></div>
                    <div class="stream-name">{{ stream.name }}</div>
                  </div>
                </div>
              </div>
              <div
                  class="border"
              ></div>
              <div
                  class="triangle"
              ></div>
            </div>
          </div>
          <div class="none"></div>
        </div>
      </div>
    </div>
    <div class="area-container">
      <div class="area-item">
        <div class="title">食堂直播主页</div>
        <div class="danmu-input">
          <input type="text" v-model="danmuMessage" @keyup.enter="sendDanmu(danmuMessage)" placeholder="输入弹幕">
          <button @click="sendDanmu(danmuMessage)">发送</button>
        </div>

        <div class="danmu-container">
          <div v-for="(danmu, index) in danmus" :key="index" class="danmu" :style="{ top: danmu.top + 'px' }">{{ danmu.text }}</div>
        </div>
        <div class="live-room-list">
          <div>
            <div>
              <div
                  class="cdn-ico"
              >
              </div>
            </div>
          </div>
        </div>

        </div>
      </div>
    </div>



</template>

<script>
// import DishDetailCard from '../../components/DishDetailCard.vue'; //
import { getTodayDishes } from '@/api/dishes';
import { getAllActiveStreams } from '@/api/live';
import { baseURL } from '@/utils/request'; // 导入baseURL
import Hls from 'hls.js';
import { Client } from '@stomp/stompjs';
import SockJS from 'sockjs-client';

export default {

  // components: {
  //   DishDetailCard
  // },
  data() {
    return {
      todayDishes: [], // 用于存储今日菜品
      loadingDishes: false, // 菜品加载状态
      liveStreams: [], // 存储从后端获取的直播流信息
      currentStreamUrl: '', // 当前播放的直播流URL

      ws: null,
      stompClient: null,
      danmuMessage: '',
      danmus: [], // 用于存储接收到的弹幕

    };
  },

  async mounted() {
    this.connectWebSocket();

    await this.fetchLiveStreamUrl(); // 获取直播流地址

    //
    // var video = document.getElementById('live-video');
    // var videoSrc = 'http://localhost:8080/live/livestream.m3u8'; // 替换为您的HLS流地址
    //
    // // 视频点击事件，取消静音
    // video.addEventListener('click', function() {
    //   if (video.muted) {
    //     video.muted = false;
    //   }
    // });
    //
    // if (Hls.isSupported()) {
    //   var hls = new Hls();
    //   hls.loadSource(videoSrc);
    //   hls.attachMedia(video);
    //   hls.on(Hls.Events.MANIFEST_PARSED, function() {
    //     video.play();
    //   });
    // } else if (video.canPlayType('application/vnd.apple.mpegurl')) {
    //   video.src = videoSrc;
    //   video.addEventListener('canplay', function() {
    //     video.play();
    //   });
    // }

    this.fetchTodayDishes();

    let scrollDuration = 100; // 滚动持续30秒
    let dishesContainer = this.$el.querySelector('.dishes-scroll-container');
    dishesContainer.style.animationDuration = `${scrollDuration}s`;

  },

  methods: {

    async fetchLiveStreamUrl() {
      try {
        const response = await getAllActiveStreams();
        if (response.code === 200 && response.data) {
          this.liveStreams = response.data;
          this.currentStreamUrl = this.liveStreams[0].url; // 设置第一个直播流为默认播放
          this.initVideoPlayer(this.currentStreamUrl);
        } else {
          console.error('Error: Invalid response format or error code');
        }
      } catch (error) {
        console.error('Error fetching live stream URL:', error);
      }
    },

    switchLiveStream(streamUrl) {
      if(this.currentStreamUrl !== streamUrl) {
        this.currentStreamUrl = streamUrl;
        this.initVideoPlayer(this.currentStreamUrl);
      }
    },

    initVideoPlayer(videoSrc) {
      var video = document.getElementById('live-video');

      // 视频点击事件，取消静音
      video.addEventListener('click', function() {
        if (video.muted) {
          video.muted = false;
        }
      });

      if (Hls.isSupported()) {
        var hls = new Hls();
        hls.loadSource(videoSrc);
        hls.attachMedia(video);
        hls.on(Hls.Events.MANIFEST_PARSED, function() {
          video.play();
        });
      } else if (video.canPlayType('application/vnd.apple.mpegurl')) {
        video.src = videoSrc;
        video.addEventListener('canplay', function() {
          video.play();
        });
      }
    },

    async fetchTodayDishes() {
      this.loadingDishes = true;
      try {
        const response = await getTodayDishes();
        let dishes = response.data.reverse(); // 获取并倒序菜品数组
        this.todayDishes = [...dishes, ...dishes]; // 重复数组以创建无缝滚动效果
      } catch (error) {
        console.error('Error fetching today\'s dishes:', error);
      } finally {
        this.loadingDishes = false;
      }
    },
    getImageUrl(path) {
      return `${baseURL}${path}`;
    },


    addDanmu(danmuMessage) {
      const verticalPosition = Math.floor(Math.random() * 40);

      // const verticalPosition = Math.floor(Math.random() * this.$refs.videoContainer.clientHeight);
      const newDanmu = { text: danmuMessage, top: verticalPosition };
      this.danmus.push(newDanmu);

      console.log("TESTING33: "+newDanmu);

      setTimeout(() => {
        this.danmus.shift(); // 在一定时间后移除弹幕
      }, 10000); // 10秒后移除弹幕
    },

    connectWebSocket() {
      const socket = new SockJS('http://localhost:8080/websocket');
      this.stompClient = new Client({ webSocketFactory: () => socket });

      this.stompClient.onConnect = (frame) => {
        console.log('Connected: ' + frame);
        this.stompClient.subscribe('/topic/messages', (message) => {
          this.addDanmu(message.body);
        });
      };

      this.stompClient.activate();
    },


    sendDanmu(danmuMessage) {
      if (this.danmuMessage.trim() !== '') {
        this.addDanmu(this.danmuMessage);
        console.log("TESTING11: "+danmuMessage);

        if (this.stompClient && this.stompClient.connected) {
          this.stompClient.publish({ destination: '/app/send', body: this.danmuMessage });
          console.log("TESTING22: "+danmuMessage);

          this.danmuMessage = '';
        }
      }
    },
  },
};
</script>

<style lang="scss" scoped>

.stream-card {
  cursor: pointer;
  border: 1px solid #ddd;
  margin-bottom: 10px;
  padding: 10px;
  transition: box-shadow 0.3s;
}

.stream-card:hover {
  box-shadow: 0px 2px 5px rgba(0,0,0,0.2);
}

.stream-thumbnail {
  height: 100px; /* 或者根据您的需要设置高度 */
  background-color: #f0f0f0; /* 临时颜色，用于缩略图区域 */
  margin-bottom: 10px;
}

.stream-name {
  font-size: 1.1em;
  font-weight: bold;
  color: #333;
}


/* 横向滚动展示菜品的样式 */
.today-dishes-scroll {
  overflow: hidden; /* 隐藏滚动条 */
  white-space: nowrap;
  padding: 20px 0;
}

.dishes-scroll-container {
  display: inline-flex;
  animation: scrollDishes 200s linear infinite;
  width: 200%; // 容纳所有菜品的宽度
}

@keyframes scrollDishes {
  0% { transform: translateX(0); }
  100% { transform: translateX(-100%); } // 只滚动一半的距离
}


.dish-card {
  flex: 0 0 auto; /* 确保卡片不缩放 */
  display: inline-flex; /* 让卡片以行内flex元素展示 */
  flex-direction: column; /* 设置内容垂直排列 */
  align-items: center; /* 中心对齐卡片内容 */
  width: 120px; /* 每个卡片的宽度 */
  margin-right: 20px; /* 卡片之间的间距 */
  border: 1px solid #ccc; /* 卡片边框 */
  border-radius: 8px; /* 圆角边框 */
  overflow: hidden; /* 隐藏溢出内容 */
  background: white; /* 卡片背景色 */
  box-shadow: 0 2px 8px rgba(0,0,0,0.1); /* 卡片阴影 */
}

.dish-image {
  width: 100%; /* 图片宽度占满卡片 */
  height: 80px; /* 图片高度 */
  object-fit: cover; /* 裁剪以填充容器 */
}

.dish-info {
  padding: 2px; /* 内容区域的填充 */
}

.dish-name {
  margin: 0;
  font-size: 0.9em; /* 菜品名称的字体大小 */
  text-align: center; /* 文本居中 */
}

/* 响应式设计：在较小屏幕上调整样式 */
@media (max-width: 600px) {
  .dish-card {
    width: 120px;
  }

  .dish-image {
    height: 80px;
  }
}


.danmu-input {
  margin-top: 20px; /* 为了在标题下方留出一些空间 */
  margin-bottom: 10vh;
  text-align: center; /* 使输入框和按钮居中对齐 */
}

.danmu-input input {
  padding: 5px;
  margin-right: 5px;
}

.danmu-container {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  overflow: hidden;
}

.danmu {
  position: absolute;
  white-space: nowrap;
  color: white;
  font-size: 16px;
  animation: danmu-move 10s linear;
}

@keyframes danmu-move {
  from { right: -100%; }
  to { left: 100%; }
}



.home-wrap {
  .play-container {
    position: relative;
    z-index: 1;
    padding-bottom: 20px;

    .bg {
      position: absolute;
      top: 0;
      right: 0;
      left: 0;
      z-index: -1;
      width: 100%;
      height: 100%;
      background-color: papayawhip;
      background-position: center;
      background-repeat: no-repeat;
    }

    .slider-wrap {
      padding: 2px 0 4px 0;
    }

    .container {
      display: flex;
      justify-content: center;
      box-sizing: border-box;
      margin: 0 auto;
      height: calc($w-1100 / $video-ratio);

      .left {
        position: relative;
        display: inline-block;
        overflow: hidden;
        flex-shrink: 0;
        box-sizing: border-box;
        margin-right: 20px;
        width: $w-1100;
        height: 100%;
        border-radius: 4px;
        background-color: rgba($color: #000000, $alpha: 0.3);


        .cdn-ico {
          position: absolute;
          top: -9px;
          right: -10px;
          z-index: 2;
          width: 70px;
          height: 32px;
          background-color: #f87c48;
          color: white;
          transform: rotate(45deg);
          transform-origin: bottom;

          .txt {
            margin-top: 11px;
            margin-left: 20px;
            background-image: initial !important;
            font-size: 14px;
          }
        }

        .cover {
          position: absolute;
          background-position: center center;
          background-size: cover;
          filter: blur(10px);

          inset: 0;
        }

        :deep(canvas) {
          position: absolute;
          top: 50%;
          left: 50%;
          max-width: $w-1100;
          max-height: calc($w-1100 / $video-ratio);
          transform: translate(-50%, -50%);

          user-select: none;
        }

        :deep(video) {
          position: absolute;
          top: 50%;
          left: 50%;
          max-width: $w-1100;
          max-height: calc($w-1100 / $video-ratio);
          transform: translate(-50%, -50%);

          user-select: none;
        }

        &:hover {
          .join-btn {
            display: inline-flex !important;
          }
        }

        .join-btn {
          position: absolute;
          top: 50%;
          left: 50%;
          z-index: 20;
          display: none;
          align-items: center;
          align-items: center;
          justify-content: center;
          box-sizing: border-box;
          width: 80%;
          transform: translate(-50%, -50%);

          &.show {
            display: inline-flex !important;
          }

          .btn {
            padding: 14px 26px;
            border: 2px solid rgba($color: $theme-color-gold, $alpha: 0.5);
            border-radius: 6px;
            background-color: rgba(0, 0, 0, 0.3);
            color: $theme-color-gold;
            font-size: 16px;
            cursor: pointer;

            &:hover {
              background-color: $theme-color-gold;
              color: white;
            }
          }
        }
      }

      .right {
        display: inline-block;
        overflow: scroll;
        flex-shrink: 0;
        box-sizing: border-box;
        padding: 12px 10px;
        height: 100%;
        border-radius: 4px;
        background-color: rgba($color: #000000, $alpha: 0.3);

        .list {
          .item {
            position: relative;
            box-sizing: border-box;
            margin-bottom: 10px;
            width: 200px;
            height: 110px;
            border-radius: 4px;
            background-color: rgba($color: #000000, $alpha: 0.3);
            cursor: pointer;

            &:last-child {
              margin-bottom: 0;
            }

            .hidden {
              position: relative;
              overflow: hidden;
              width: 200px;
              height: 110px;

              .cdn-ico {
                position: absolute;
                top: -9px;
                right: -9px;
                z-index: 2;
                width: 60px;
                height: 28px;
                background-color: #f87c48;
                color: white;
                transform: rotate(45deg);
                transform-origin: bottom;

                .txt {
                  margin-left: 10px;
                  background-image: initial !important;
                  font-size: 12px;
                  line-height: 0.8;
                }
              }
            }

            .border {
              position: absolute;
              top: 0;
              right: 0;
              bottom: 0;
              left: 0;
              z-index: 3;
              border: 2px solid $theme-color-gold;
              border-radius: 4px;
            }

            .triangle {
              position: absolute;
              top: 50%;
              left: 0;
              display: inline-block;
              border: 5px solid transparent;
              border-right-color: $theme-color-gold;
              transform: translate(-100%, -50%);
            }

            &.active {
              &::before {
                background-color: transparent;
              }
            }

            &:hover {
              &::before {
                background-color: transparent;
              }
            }

            &::before {
              position: absolute;
              display: block;
              width: 100%;
              height: 100%;
              border-radius: 4px;
              background-color: rgba(0, 0, 0, 0.4);
              content: '';
              transition: all cubic-bezier(0.22, 0.58, 0.12, 0.98) 0.4s;
            }

            .txt {
              position: absolute;
              bottom: 0;
              left: 0;
              box-sizing: border-box;
              padding: 4px 8px;
              width: 100%;
              border-radius: 0 0 4px 4px;
              background-image: linear-gradient(
                      -180deg,
                      rgba(0, 0, 0, 0),
                      rgba(0, 0, 0, 0.6)
              );
              color: white;
              text-align: initial;
              font-size: 13px;

            }
          }
        }

        .none {
          width: 200px;
          color: white;
          text-align: center;
          font-size: 14px;
        }
      }
    }
  }

  .area-container {
    box-sizing: border-box;
    margin: 10px auto;
    width: $w-1350;

    .area-item {
      .title {
        padding: 2px 0;
        font-size: 26px;
      }

      .live-room {
        display: inline-block;
        margin-right: 32px;
        margin-bottom: 10px;
        width: 300px;
        cursor: pointer;

        .cover {
          position: relative;
          overflow: hidden;
          width: 100%;
          height: 150px;
          border-radius: 8px;
          background-position: center center;
          background-size: cover;

          .cdn-ico {
            position: absolute;
            top: -10px;
            right: -10px;
            z-index: 2;
            width: 70px;
            height: 28px;
            background-color: #f87c48;
            color: white;
            transform: rotate(45deg);
            transform-origin: bottom;

            .txt {
              margin-left: 18px;
              background-image: initial !important;
              font-size: 13px;
            }
          }

          .txt {
            position: absolute;
            bottom: 0;
            left: 0;
            box-sizing: border-box;
            padding: 4px 8px;
            width: 100%;
            border-radius: 0 0 4px 4px;
            background-image: linear-gradient(
                    -180deg,
                    rgba(0, 0, 0, 0),
                    rgba(0, 0, 0, 0.6)
            );
            color: white;
            text-align: initial;
            font-size: 13px;
          }
        }

        .desc {
          margin-top: 4px;
          font-size: 14px;

        }
      }
    }
  }

  .foot {
    margin-top: 10px;
    text-align: center;
  }
}


</style>
